package com.surpassun.emall.repository;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.surpassun.emall.model.Statistics;
import com.surpassun.emall.util.QueryUtil;
import com.surpassun.emall.util.Validator;

/**
 *
 * @author Denis
 */
@Repository
public class StatisticsRepository extends AbstractRepository<Statistics> {
	
	private final String QUERY_GET_TOTAL_BY_FIELD_AND_REFERENCEID = "Statistics_GetTotalByFieldAndReferenceId";
	private final String QUERY_GET_TOP_ITEMS_BY_FIELD = "Statistics_GetTopItemsByField";

    public StatisticsRepository() {
        super(Statistics.class);
    }
    
    public Statistics getExisted(String field, long referenceId) {
    	String[] fields = new String[]{"field", "referenceId"};
    	Object[] values = new Object[]{field, referenceId};
    	String[] restrictedTypes = new String[]{QueryUtil.EQUAL, QueryUtil.EQUAL};
    	List<Statistics> result = super.getByFields(fields, values, restrictedTypes);
    	if (Validator.isNotNull(result) && result.size() > 0) {
    		return result.get(0);
    	} else {
    		return null;
    	}
    }
    
    public int getTotal(String field, long referenceId) {
    	Query query = super.getEntityManager().createNamedQuery(QUERY_GET_TOTAL_BY_FIELD_AND_REFERENCEID);
    	query.setParameter("field", field);
    	query.setParameter("referenceId", referenceId);
    	return ((Integer)query.getSingleResult()).intValue();
    }
    
    @SuppressWarnings("unchecked")
	public List<Long> getTopItems(String field, int number) {
    	Query query = super.getEntityManager().createNamedQuery(QUERY_GET_TOP_ITEMS_BY_FIELD);
    	query.setParameter("field", field);
    	query.setMaxResults(number);
    	return (List<Long>)query.getResultList();
    }
}